// packageShop/pages/shopSearch/shopSearch.js

var util = require('../../../utils/util')   //引入配置公共请求接口
const app=getApp();
var configUrl = require('../../../config/config')   //引入配置接口文件
Page({

  /**
   * 页面的初始数据
   */
  data: {
    footprintGuid: '', //足迹全局id
    isShowPartnerAll: true,
    CustomBar: app.globalData.CustomBar,
    statusHeight:app.globalData.StatusBar,
    ispopShow:false,
    zhSelect:false,
    isFocusSearch:false,
    isShowHistory:true,  //历史搜索
    xlShow:false,
    zhShow:false,
    jgShow:false,
    searchNew:false,
    ishiddenHestry:true,
    classifyList:[],  //搜索类目列表
    page:1,
    classPageGo:false,
    evArr:[], //筛选条件
    placeholderText: '请输入搜索商品名称'
  },
   //展开合伙人信息
   showPartnerAll: function () {
    this.setData({
      isShowPartnerAll: !this.data.isShowPartnerAll,
    })
  },
  //展示合伙人二维码
    partnerCode: function (e) {
    // this.setData({
    //   showPartnerCodePop: true,
    // })
    let codeImg=e.target.dataset.url
    wx.previewImage({
      urls:[codeImg],
      current: codeImg, // 当前显示图片的http链接
     })
  },
  //关闭合伙人二维码
  closeCodePop: function () {
    this.setData({
      showPartnerCodePop: false,
    })
  },
  //拨打合伙人电话
  partnerPhone: function () {
    let that = this;
    wx.makePhoneCall({
      phoneNumber: that.data.partnerInfo.partnerPhone,
    })
  },
  switchStyles(e){ //切换布局样式
    var val=e.currentTarget.dataset.val
    if(val==1){
      if(this.data.isShowBody==3 || this.data.isShowBody==1){
        this.setData({
          isShowBody:2
        })
      }else if(this.data.isShowBody==3 || this.data.isShowBody==2){
        this.setData({
          isShowBody:1
        })  
      }
    }else{
      this.setData({
        historyLsit:wx.getStorageSync('historyLsit')
      })  
    }
  },
  searchBtn(e){  //触发搜索商品
    var that=this;
    var parms={keyword:e.detail}
    var historyLsit=wx.getStorageSync('historyLsit')
    if(e.currentTarget.dataset.type==1){
      parms={keyword:e.currentTarget.dataset.val}
      historyLsit.splice(historyLsit.indexOf(e.currentTarget.dataset.val),1)
      historyLsit.unshift(e.currentTarget.dataset.val)
      wx.setStorageSync('historyLsit', historyLsit)
    }else{
      if(!e.detail){
        return;
      }
      if(historyLsit){
        var newArr=[e.detail]
        for(var i=0;i<20;i++){
          if(historyLsit[i]!=e.detail){
            if(historyLsit[i]){
              newArr.push(historyLsit[i])
            }
            
          }
        }
        historyLsit= newArr
      }else{
        historyLsit=[e.detail]
      }
      wx.setStorageSync('historyLsit', historyLsit)
    }
    this.setData({
      keyword:parms.keyword,
      value:parms.keyword,
      showNotMove:false
    }) 
    if(this.data.cominFrom=='coupon'){   //优惠券进入添加查询条件
      parms.couponId=this.data.parmsData.couponId
    }
    parms.provinceCode=wx.getStorageSync('addrCode').provinceCode
    that.setData({
      parms:parms,
      page:1
    })
    app.reqFun.requestJson('post',configUrl.searchShopData,parms,(res)=>{
      if(res.data.success==1){ 
        this.setData({
          isShowBody:2,
          classifyList:[],
          catId:'',
        }) 
        if(res.data.data){
         that.setData({
           screenData1:res.data.data.productScreenDTOList,      //筛选条件
           screenData2:res.data.data.productCategoryFacetDtos,      //筛选目录
           shopList:res.data.data.solrProductDtos.records ,    //筛选商品列表
           pageTatol:res.data.data.solrProductDtos.totalPages  //总页数
         })
        }else{
          that.setData({
           shopList:[]
          })  
        }
      }    
    })
   
  },
  changeSearchData(e){  //搜索匹配类目
    var that=this;
    if(!e.detail){
      that.setData({
        classifyList:[],
        isShowBody:3,
        isShowHistory:true,
        historyLsit:wx.getStorageSync('historyLsit')
      })
      return;
    }
    var parms={ name:e.detail }
    if(that.data.cominFrom=='coupon'){  //优惠券进入带上优惠券ID 搜索
      parms.couponId=that.data.parmsData.couponId
    }
    app.reqFun.requestJson('get',configUrl.searchClassify,parms,(res)=>{
      if(res.data.success==1){ 
        that.setData({
          isShowHistory:false,
          classifyList:res.data.data
        })
      }    
    },true)
  },
  async classifyGoSearch(e){  //类目搜索商品
    var that=this;
    var parms={}
    if(that.data.classPageGo){    //导航点击类目
      var ids=e.id
      var arrID=ids&&ids.split(",")
      if(arrID.length>1){
        parms.cats=arrID
      }else{
        parms.cat=ids
      }
      that.setData({
        value:e.name,
        catId:e.id,
        keyword:'',
        showNotMove:false,
        isShowBody:2,
        classifyList:[],
        historyLsit:wx.getStorageSync('historyLsit')  
      })
    }else{     //点击搜索类目
      var historyLsit=wx.getStorageSync('historyLsit') 
      if(historyLsit){
        var newArr=[e.currentTarget.dataset.val.name]
        for(var i=0;i<20;i++){
          if(historyLsit[i]!=e.currentTarget.dataset.val.name){
            if(historyLsit[i]){
              newArr.push(historyLsit[i])
            }    
          }
        }
        historyLsit= newArr
      }else{
        historyLsit=[e.currentTarget.dataset.val.name]
      }
      wx.setStorageSync('historyLsit', historyLsit)
      var classInfo=e.currentTarget.dataset.val
      if(!parms.cats){
        parms.cat=classInfo.id
      }
      that.setData({
        value:classInfo.name,
        catId:classInfo.id,
        keyword:'',
        showNotMove:false,
        isShowBody:2,
        classifyList:[],
        historyLsit:wx.getStorageSync('historyLsit') 
      })
    }
    if(this.data.cominFrom=='coupon'){   //优惠券进入添加查询条件
      parms.couponId=this.data.parmsData.couponId
    }
    parms.provinceCode=wx.getStorageSync('addrCode').provinceCode
    
    that.setData({
      parms:parms,
      page:1
    })
    
    parms.sort=this.data.keyword?"":"sort_random"
    await app.reqFun.requestJson('post',configUrl.searchShopData,parms,(res)=>{
      if(res.data.success==1){ 
       if(res.data.data){
        that.setData({
          screenData1:res.data.data.productScreenDTOList,      //筛选属性
          screenData2:res.data.data.productCategoryFacetDtos,      //筛选类目  
          shopList:res.data.data.solrProductDtos.records.length>0?res.data.data.solrProductDtos.records:[],    //筛选商品列表
          pageTatol:res.data.data.solrProductDtos.totalPages  //总页数        
        })
        //默认匹配选中类目
        if(!that.data.classPageGo){   //单类目
          that.selectThisClass({cat:e.currentTarget.dataset.val.id})
        }else{  
          var ids=e.id
          var cats=ids&&ids.split(",")
          if(cats.length==1){
            that.selectThisClass({cat:cats[0]})
          }
        }
       }else{
         that.setData({
          shopList:[]
         }) 
       }
      }
      
    })
  },
  deleteHistory(e){  //删除历史搜索
    var data=e.currentTarget.dataset.val
    var list=wx.getStorageSync('historyLsit')
    for(var i=0;i<list.length;i++){
      if(list[i]==data){
        list.splice(i,1)
      }
    }
    this.setData({
      historyLsit:list
    })
    wx.setStorageSync('historyLsit', list)
  },
  clearAllHistory(){
     wx.removeStorageSync('historyLsit')
     this.setData({
      historyLsit:[]
     })
  },
  searchSort(parms){  //排序
    var that=this
    if(that.data.keyword){
      parms.keyword=that.data.keyword
    }
    if(that.data.catId){
      parms.cat=that.data.catId
    }
    that.setData({  
      parms:parms, //当前排序搜索值
      page:1    //重置搜索page页
    })
    app.reqFun.requestJson('post',configUrl.searchShopData,parms,(res)=>{
      if(res.data.success==1){ 
        if(res.data.data){
          that.setData({
            shopList:res.data.data.solrProductDtos.records     //筛选商品列表
           })
        }
       
      }    
    })
  },
  lastLoad(parms){  //触底加载数据
    var that=this;
    app.reqFun.requestJson('post',configUrl.searchShopData,parms,(res)=>{
      if(res.data.success==1){ 
        var list=that.data.shopList
        for(let val of res.data.data.solrProductDtos.records){
          list.push(val)
        }
       that.setData({
        shopList: list    //筛选商品列表
       })
      }    
    })
  },
  heightPrice(e){
    this.setData({
      heightPrice:e.detail.value
    })
  },
  lowPrice(e){
    this.setData({
      lowPrice:e.detail.value
    })
  },
  selectThisClass(e){  //筛选选择类目触发
    var that=this
    var cat=''
    if(e.cat){
      cat=e.cat
    }else{
      cat=e.currentTarget.dataset.id
    }  
    var parms=this.data.parms  
    parms.cat=cat
    delete parms.ev
    var classList=this.data.screenData2
    for(let val of classList){
      val.ischeck=false
      if(val.id==cat){
        val.ischeck=true
      }
    }
    var arr=[]
    if(this.data.lowPrice){
      arr.push("M"+this.data.lowPrice)
    }
    if(this.data.heightPrice){
      arr.push("L"+this.data.heightPrice)
    }
    if(arr.length>0){
      parms.exprice=arr.join(" ")
    } 
    this.setData({
      screenData2:classList,
      parms:parms
    })
    app.reqFun.requestJson('post',configUrl.searchShopData,parms,(res)=>{
      if(res.data.success==1){ 
       if(res.data.data){
        that.setData({
          screenData1:res.data.data.productScreenDTOList,      //筛选属性
          shopList:res.data.data.solrProductDtos.records,    //筛选商品列表
          pageTatol:res.data.data.solrProductDtos.totalPages,  //总页数
          totalRows:res.data.data.solrProductDtos.totalRows,
          searchNew:true
        })
       }else{
         that.setData({
          shopList:[],
          totalRows:0,
         })
        
       }
      }    
    })
  },
  selectProperty(e){  //选择属性筛选触发
    var that=this;
    var list=this.data.screenData1
    var arr=this.data.evArr
    var parms=this.data.parms
    var sId=e.currentTarget.dataset.pid+"_"+e.currentTarget.dataset.id
    for(let val of list){
      for(let val2 of val.pmsProductScreenDTOS){
        if(val2.id==e.currentTarget.dataset.id){
          if(val2.ischeck){
            val2.ischeck=false
            for(var i=0;i<arr.length;i++){
              if(arr[i].indexOf(e.currentTarget.dataset.id)>-1){
                arr.splice(i,1)
              }
            }
          }else{
            val2.ischeck=true
            arr.push(sId)
          }
        }
      }
    }
    parms.ev= arr.join("@")
    var arr2=[]
    if(this.data.lowPrice){
      arr2.push("M"+this.data.lowPrice)
    }
    if(this.data.heightPrice){
      arr2.push("L"+this.data.heightPrice)
    }
    if(arr2.length>0){
      parms.exprice=arr2.join(" ")
    }   
    this.setData({
      evArr:arr,
      screenData1:list,
      parms:parms
    })
    app.reqFun.requestJson('post',configUrl.searchShopData,parms,(res)=>{
      if(res.data.success==1){ 
       if(res.data.data){
        that.setData({
          shopList:res.data.data.solrProductDtos.records,    //筛选商品列表
          pageTatol:res.data.data.solrProductDtos.totalPages,  //总页数
          totalRows:res.data.data.solrProductDtos.totalRows,
          searchNew:true
        })
       }else{
         that.setData({
          shopList:[],
          totalRows:0,
         })
        
       }
      }    
    })
  },
  clearParemsPrice(e){  //辅助价格筛选过滤
    var parms=this.data.parms
    delete parms.exprice
    this.setData({
      parms:parms
    })
  },
  selectPrice(e){   //价格筛选触发
    var that=this;
    var parms=this.data.parms
    var arr2=[]
    var lowp=this.data.lowPrice
    var hightp= this.data.heightPrice
    if(lowp && hightp){
      if(parseInt(lowp) > parseInt(hightp)){
        this.setData({
          lowPrice:hightp,
          heightPrice:lowp
        })
        arr2.push("M"+hightp)
        arr2.push("L"+lowp)
      }else{
        this.setData({
          lowPrice:lowp,
          heightPrice:hightp
        })
        arr2.push("M"+lowp)
        arr2.push("L"+hightp)
      }
      
    }else if(this.data.lowPrice && !this.data.heightPrice){
      arr2.push("M"+this.data.lowPrice)
    }else if(!this.data.lowPrice && this.data.heightPrice){
      arr2.push("L"+this.data.heightPrice)
    }
    
    if(arr2.length>0){
      parms.exprice=arr2.join(" ")
    }
    this.setData({
      parms:parms
    }) 
    console.log(parms)
    app.reqFun.requestJson('post',configUrl.searchShopData,parms,(res)=>{
      if(res.data.success==1){ 
       if(res.data.data){
        that.setData({
          shopList:res.data.data.solrProductDtos.records,    //筛选商品列表
          pageTatol:res.data.data.solrProductDtos.totalPages,  //总页数
          totalRows:res.data.data.solrProductDtos.totalRows,
          searchNew:true
        })
       }else{
         that.setData({
          shopList:[],
          totalRows:0,
         })
        
       }
      }    
    }) 
  },
  resetSearch(){  //重置筛选条件
    var that=this;
    var parms=this.data.parms
    delete parms.ev
    if(parms.keyword){
      delete parms.cat
    }
    if(parms.couponId){
      delete parms.cat
    }
    delete parms.exprice
    this.setData({
      heightPrice:"",
      lowPrice:''
    })
    app.reqFun.requestJson('post',configUrl.searchShopData,parms,(res)=>{
      if(res.data.success==1){ 
        if(res.data.data){
         that.setData({
           screenData1:res.data.data.productScreenDTOList,      //筛选条件
           screenData2:res.data.data.productCategoryFacetDtos,      //筛选目录
           shopList:res.data.data.solrProductDtos.records ,    //筛选商品列表
           pageTatol:res.data.data.solrProductDtos.totalPages,  //总页数
           totalRows:res.data.data.solrProductDtos.totalRows,
           searchNew:true,
         })
        }else{
          that.setData({
           shopList:[],
           totalRows:0,
           searchNew:true,
          })  
        }
      }    
    })
  },
  goGoosInfo(e){  //进入商品详情
    wx.navigateTo({
      url: '../goodsInfo/goodsInfo?id='+e.currentTarget.dataset.id,
    })
  },
  getCouponSearch(parms){  //优惠券查询
    var that=this;
    that.setData({
      parms:parms,
      page:1
    })
    app.reqFun.requestJson('post',configUrl.searchShopData,parms,(res)=>{
      if(res.data.success==1){ 
        this.setData({
          isShowBody:2,
          classifyList:[],
          catId:'',
        }) 
        if(res.data.data){
         that.setData({
           screenData1:res.data.data.productScreenDTOList,      //筛选条件
           screenData2:res.data.data.productCategoryFacetDtos,      //筛选目录
           shopList:res.data.data.solrProductDtos.records ,    //筛选商品列表
           pageTatol:res.data.data.solrProductDtos.totalPages  //总页数
         })
        }else{
          that.setData({
           shopList:[]
          })  
        }
      }    
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff'
    })
    this.setData({
      historyLsit:wx.getStorageSync('historyLsit'),
      ishiddenHestry:false,
    })
    if(options.type=='s'){  //搜索进入
      console.log(options.type)
      this.setData({
        isFocusSearch:true,
        isShowBody:3
      }) 
    }else if(options.type=='c'){  //分类导航进入
      this.setData({
        isFocusSearch:false,
        isShowBody:3
      }) 
      if(options.classifyId){   //商品导航进入
        this.setData({
          classPageGo:true,
          isShowBody:2,
        })
        var json={
          id:options.classifyId,
          name:options.className
        }
        this.classifyGoSearch(json)
      }
    }
    if (options.placeholderText) {
      this.setData({
        placeholderText: options.placeholderText
      })
    }
    //优惠券进入页面
    if(options.from=='coupon'){ 
      console.log(options)
      var couponId=options.couponId
      var parms={
        couponId:couponId,
        provinceCode:wx.getStorageSync('addrCode').provinceCode
      }
      this.setData({
        ishiddenHestry:true,
        parmsData:parms,
        cominFrom:'coupon',
      })
      this.getMycouponList(couponId)
      this.getCouponSearch(parms)
    }


  },
  getMycouponList(couponId){
    var that=this;
    app.reqFun.requestJson('GET', configUrl.getCouponInfo+couponId , '', (response) => {
      const res=response.data
      if (res.success == 1) {
        that.setData({
          couponInfoData:res.data
        })
      }
    })    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      footprintGuid: util.guid()
    })
    setTimeout(()=>{
      this.setData({
        partnerInfo:getApp().globalData.partnerInfo
      })
      },500)
    //保存访问足迹
    app.saveAccessFootprint(this.data.footprintGuid, 'searchList', null)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var parms=this.data.parms
    parms.page=1
    parms.provinceCode=wx.getStorageSync('addrCode').provinceCode
    app.reqFun.requestJson('post',configUrl.searchShopData,parms,(res)=>{
      if(res.data.success==1){ 
       that.setData({
        shopList:res.data.data.solrProductDtos.records     //筛选商品列表
       })
      }    
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var page=this.data.page+1
    var parms=this.data.parms
    var tatol=this.data.pageTatol
    parms.page=page
    if(page>tatol){
      this.setData({
        showNotMove:true
      })
      return;
    }
    this.setData({
      page:page
    })
    this.lastLoad(parms)
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  goreBack:function(e){
    wx.navigateBack({
      delta: 1
    })
  },
  showPopup(e) {  //条件查询按钮
    var that=this;
    var type=e.currentTarget.dataset.val
    var select=e.currentTarget.dataset.select
    var parms=this.data.parms
    parms.page=1
    if(type=="zh"){  //综合排序
      this.setData({
        zhColor:'#16BC83',
        zhSelect:select?false:true,
        xlColor:"#333",
        xlSelect:false,
        jgColor:"#333",
        jgSelect:false,
        sxColor:"#333",
        sxSelect:false,
        zhShow:true,
        xlShow:false,
        jgShow:false,
        showNotMove:false
      })
      parms.sort=this.data.keyword?"":"sort_random"
      that.searchSort(parms)
    }else if(type=="xl"){   //销量排序
      this.setData({
        xlColor:'#16BC83',
        xlSelect:select?false:true,
        jgColor:"#333",
        jgSelect:false,
        zhColor:"#333",
        zhSelect:false,
        sxColor:"#333",
        sxSelect:false,
        zhShow:false,
        xlShow:true,
        jgShow:false,
        showNotMove:false
      })
      parms.sort=this.data.xlSelect?"sort_sale_desc":"sort_sale_asc"
      that.searchSort(parms)
    }else if(type=="jg"){   //价格排序   
      this.setData({
        jgColor:'#16BC83',
        jgSelect:select?false:true,
        xlColor:"#333",
        xlSelect:false,
        zhColor:"#333",
        zhSelect:false,
        sxColor:"#333",
        sxSelect:false,
        zhShow:false,
        xlShow:false,
        jgShow:true,
        showNotMove:false
      })
      parms.sort=this.data.jgSelect?'sort_price_asc':'sort_price_desc';
      that.searchSort(parms)
    }else{
      this.setData({ ispopShow: true, showNotMove:false});
    }
  },

  onClose() {   //关闭弹出层
    this.setData({ ispopShow: false });
  },
})

